package com.app.controller;

import com.app.common.EducationTool;
import com.app.model.*;
import com.app.service.*;
import com.app.util.*;
import com.app.vo.WorkApplyVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;


@Controller
@RestController
public class WorkApplyController {


    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    UserService userService;
    @Autowired
    CustomerService customerService;
    @Autowired
    WorkApplyService workApplyService;
    @Autowired
    JobPublishService jobPublishService;
    @Autowired
    ComResumeNumberService comResumeNumberService;
    @Autowired
    ComRecruitersService comRecruitersService;
    @Autowired
    CusEducationService cusEducationService;
    @Autowired
    CusWorkExperienceService cusWorkExperienceService;
    @Autowired
    EnterpriseService enterpriseService;


    //增/改
    @PostMapping("/insertWorkApply")
    public Result<Object> groupWorkExp(HttpServletRequest request) throws IOException {
        int publishId = Integer.parseInt(request.getParameter("publishId"));
        JSONObject json = new JSONObject();
        String token = request.getHeader("token");
//        String id = request.getParameter("id");
        if (token == null) {
            return Result.error(405,"token不存在");
        }
        String mobile = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405,"用户不存在");
        }
        WorkApplyModel model = new WorkApplyModel();
        model.setPublishId(publishId);
        CustomerModel cus = customerService.getCustomerById(user.getCId());
        List<WorkApplyModel> modelList = workApplyService.getWorkApplyByCustomer(cus.getId(), publishId);
        if (modelList != null && modelList.size() > 0) {
            return Result.error(200,"已投递过该职位");
        }
        JobPublishModel pub = jobPublishService.findAllJobById(publishId);
        model.setEId(pub.getEnrollId());
        model.setCustomerId(cus.getId());
        model.setCrtTime(CommonHelp.getNowTimestamp());
        workApplyService.insert(model);
        ComResumeNumberModel numberModel = comResumeNumberService.getModelByrId(pub.getRecId());
        if (numberModel==null) {
            numberModel = new ComResumeNumberModel();
            numberModel.setNumber(1);
            numberModel.setComId(pub.getEnrollId());
            numberModel.setPid(pub.getId());
            numberModel.setRid(pub.getRecId());
            comResumeNumberService.insert(numberModel);
        }else{
            numberModel.setNumber(numberModel.getNumber()+1);
            comResumeNumberService.update(numberModel);
        }
        UserModel userModel = userService.getUserByRId(pub.getRecId());
        SMSUtils.deliver(userModel.getMobile());//短信通知HR
        return Result.success(null);
    }

    //删除
    @PostMapping("/delWorkApply")
    public String delWorkExp(@RequestParam("id") int id) {
        JSONObject json = new JSONObject();
        try {
            if (id > 0) {
                workApplyService.delete(id);
            } else {
                json.put("code", "0");
                json.put("msg", "请输入ID");
            }

        } catch (Exception e) {
            System.out.println(e);
        }
        json.put("code", "1");
        json.put("msg", "成功");
        return json.toString();
    }

    //根据用户id查询投递简历
    @GetMapping("/getWorkApplyListByCusId")
    public Result<Object> List(HttpServletRequest request) throws ParseException {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405,"token不存在");
        }
        String mobile = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405,"用户不存在");
        }
        CustomerModel cus = customerService.getCustomerById(user.getCId());

        List<WorkApplyModel> modelList = workApplyService.getWorkApplyByPublishId(Integer.valueOf(cus.getId()));

        if (modelList != null && modelList.size() > 0) {
            return Result.success(modelList);
        }

        return Result.success(null);
    }

    //根据招聘信息ID查询用户简历
    @GetMapping("/getWorkApplyListByPublishId")
    public Result<Object> getWorkExp(HttpServletRequest request) throws ParseException {
        JSONObject json = new JSONObject();
        String id = request.getParameter("id");
        List<WorkApplyModel> modelList = workApplyService.getWorkApplyByPublishId(Integer.valueOf(id));
        if (modelList != null && modelList.size() > 0) {
            return Result.success(modelList);
        }
        return Result.success(null);

    }

    //根据招聘信息ID查询cus表
    @GetMapping("/getWorkApplyByCustomerId")
    public Result<Object> getWorkCus(HttpServletRequest request,Integer page,Integer limit) throws Exception {
        JSONObject json = new JSONObject();
        String id = request.getParameter("id");
        Page<WorkApplyModel> pageList = workApplyService.getWorkApplyByCustomerId(Integer.valueOf(id),page,limit);
        List<WorkApplyModel> list = pageList.getRecords();
        int count = (int)pageList.getTotal();
        WorkApplyVo vo = new WorkApplyVo();
        vo.setCount(count);
        vo.setList(list);
        return Result.success(vo);

    }

    //企业获取收到的简历
    @GetMapping("/getWorkApplyByCom")
    public Result<Object> getWorkApplyByCom(Integer page,Integer limit,HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405,"token不存在");
        }
        String mobile = TokenUtils.verify(token);
        UserModel user = null;
        user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405,"用户不存在");
        }
        ComRecruitersModel com = null;
        if (mobile != null && !mobile.equals("false")) {
            user = userService.getUserByMobile(mobile);
            com = comRecruitersService.getComRecruitersById(user.getRId());
        }
        Page<WorkApplyModel> pageList = workApplyService.getWorkApplyByComId(com.getComId(),page,limit);
        List<WorkApplyModel> list = pageList.getRecords();
        int count = (int)pageList.getTotal();
        for (int i = 0; i < list.size(); i++) {
            CustomerModel cus = customerService.getCustomerById(list.get(i).getCustomerId());
            //计算年龄
            if (cus.getBirthday() != null) {
                Timestamp time = new Timestamp(new SimpleDateFormat("yyyy-MM-dd").parse(cus.getBirthday() + "-01").getTime());
                String date = DateUtil.yearCompare(time, CommonHelp.getNowTimestamp());
                cus.setBirthday(date);
            } else {
                cus.setBirthday("0岁");
            }
            //判断性别
            if (cus.getSex() == 1) {
                cus.setSexText("男");
            } else {
                cus.setSexText("女");
            }
            if (StringTool.isEmpty(cus.getJobText())) {
                cus.setJobText("暂无状态");
            }
            //学历
            List<CusEducationModel> education = cusEducationService.getEducationByCustomerId(cus.getId());
            String eduName = "";
            if (education != null && education.size() > 0)//学历
            {
//                        cus.setEducation(education.get(0).getEducation());

                for (int j = 0; j < education.size(); j++) {

                    for (int k = 0; k < EducationTool.EDUCATION_VO_LIST.size(); k++) {
                        if(education.get(j).getEducation()==EducationTool.EDUCATION_VO_LIST.get(k).getId())
                        {
                            cus.setEducationText(EducationTool.EDUCATION_VO_LIST.get(k).getData());
                        }
                    }
                }
                if(cus.getEducationText()==null||cus.getEducationText()=="")
                {
                    cus.setEducationText("暂无学历");
                }
            } else {
                cus.setEducationText("暂无学历");
            }
            //工作经验
            List<CusWorkExperienceModel> workExpList = cusWorkExperienceService.getWorkExpList(cus.getId());

            if (workExpList != null && workExpList.size() > 0) {
                Timestamp time2 = new Timestamp(new SimpleDateFormat("yyyy-MM-dd").parse(workExpList.get(0).getWorkTimeStart() + "-01").getTime());
                String date2 = DateUtil.yearCompare(time2, CommonHelp.getNowTimestamp());
                cus.setWorkTimeStart(date2 + "年");

            } else {
                cus.setWorkTimeStart("无经验");
            }

            if (cus.getJobStatus() == 1) {
                cus.setJobText("离职-随时到岗");
            } else if (cus.getJobStatus() == 2) {
                cus.setJobText("在职-月内到岗");
            } else if (cus.getJobStatus() == 3) {
                cus.setJobText("在职-考虑机会");
            } else if (cus.getJobStatus() == 4) {
                cus.setJobText("在职-暂不考虑");
            }else{
                cus.setJobText("暂无状态");
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String bir = sdf.format(list.get(i).getCrtTime());
            list.get(i).setFormatTime(bir);
            UserModel cusUser = userService.getUserByCustomerId(cus.getId());
            cus.setUser(cusUser);
            list.get(i).setCustomer(cus);
        }
        WorkApplyVo vo = new WorkApplyVo();
        vo.setList(list);
        vo.setCount(count);
        return Result.success(vo);
    }

    //个人投递过的岗位
    @GetMapping("/getWorkApplyByCustomer")
    public Result<Object> getWorkApplyByCustomer(HttpServletRequest request,Integer page,Integer limit) throws Exception {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405,"token不存在");
        }
        String mobile = TokenUtils.verify(token);
        UserModel user = null;
        user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405,"用户不存在");
        }
        CustomerModel cus = null;
        if (mobile != null && !mobile.equals("false")) {
            user = userService.getUserByMobile(mobile);
            cus = customerService.getCustomerById(user.getCId());
        }
        Page<WorkApplyModel> pageList = workApplyService.getWorkApplyByCustomerId(cus.getId(),page,limit);
        List<WorkApplyModel> list = pageList.getRecords();
        int count = (int)pageList.getTotal();
        if(list!=null)
        {
            for (int i = 0; i < list.size(); i++) {
                JobPublishModel publish = jobPublishService.findAllJobById(list.get(i).getPublishId());
                if (publish != null) {
                    ComRecruitersModel com = comRecruitersService.getComRecruitersById(publish.getRecId());

                    if (com != null) {
                        EnterpriseModel enterprise = enterpriseService.findModelById(com.getComId());
                        if(enterprise.getWelfare()!=null&&enterprise.getWelfare()!="")
                        {
                            String[] str =enterprise.getWelfare().split(",");
                            List<String> welfareList = new ArrayList<>();
                            for (int j = 0; j < str.length; j++) {
                                welfareList.add(str[j]);
                            }
                            enterprise.setWelfareList(welfareList);
                        }
                        com.setEnterprise(enterprise);
                        com.setUser(userService.getUserByRId(com.getId()));
                        publish.setComRecruiters(com);
                    }
                }

                list.get(i).setJobPublish(publish);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String bir = sdf.format(list.get(i).getCrtTime());
                list.get(i).setFormatTime(bir);
            }
        }

        WorkApplyVo vo = new WorkApplyVo();
        vo.setList(list);
        vo.setCount(count);
        return Result.success(vo);
    }

    @GetMapping("/getResumeNumber")
    public Result<Object> getResumeNumber(HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405,"token不存在");
        }
        String mobile = TokenUtils.verify(token);
        UserModel user = null;
        user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405,"用户不存在");
        }
        ComRecruitersModel com = comRecruitersService.getComRecruitersById(user.getRId());

        ComResumeNumberModel number = comResumeNumberService.getModelByrId(com.getId());
        if(number!=null)
        {
            return Result.success(number.getNumber());
        }else {

            return Result.success(null);
        }

    }

    @GetMapping("delResumeNumber")
    public Result<Object> delResumeNumber(HttpServletRequest request) throws Exception {
        JSONObject json = new JSONObject();
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405,"token不存在");
        }
        String mobile = TokenUtils.verify(token);
        UserModel user = null;
        user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405,"用户不存在");
        }
        ComRecruitersModel com = comRecruitersService.getComRecruitersById(user.getRId());
        ComResumeNumberModel numberModel = comResumeNumberService.getModelByrId(com.getId());
        if(numberModel!=null)
        {
            comResumeNumberService.delete(numberModel.getId());
        }
        return Result.success("操作成功");

    }

}
